import express from 'express'
import http from '../../../../util/request.js';
var router = express.Router();

// 引入官方的加解密库
import crypto from '@wecom/crypto';

function getToken(req,res,next) {
  let {corpid,corpsecret} = req.query
  http({
    url: 'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
    method: 'GET',
    params: {corpid,corpsecret}
  }).then((result) => {
    req.token = result.access_token
    next()
  })
}


router.get('/valid_url',getToken,(req,res,next) => {
  try {
    
    const {msg_signature,timestamp,nonce,echostr} = req.query
    const token  = process.env.QIYETOKEN
  
    // 在应用详情页找到对应的token
    // 重新计算签名
    const signature = crypto.getSignature(token, timestamp, nonce, echostr);
    // 校验签名是否正确
    if (signature === msg_signature) {
      console.info('签名验证成功')
      // 在应用详情页找到对应的EncodingAESKey
      const aeskey = 'EakBs5P42NP9qmuxMRzh1eMpkw23tlj2tXEiXSr96hW';
      // 如果签名校验正确，解密 message
      const { message } = crypto.decrypt(aeskey, echostr);
      // 返回 message 信息
      res.send(message);
    }
  } catch (error) {
    console.log('error: ', error);
    res.send(error)
  }
})


router.get('/getToken',getToken,(req,res,next) => {
  const token = req.token
  res.json(req.app.locals.success(token))
})

export default router